#include "8253.h"
#include "8255.h"
#include "8259.h"
#include "isd1420.h"  

u8 minute = 0;
u8 hour = 0;
u8 ticks = 0;
u8 dpDisplayFlag = 1;                               // Flag of LED3_DP
u8 voicePlayFlag = 0;                               // Flag of playing record
u8 keepMode = 0x00;

void interrupt timer_isr(void){                     // Normal speed to present clock
    if(ticks == 0 && minute == 0 && hour == 0)      // Just start
        voicePlayFlag = 1;
    ticks++;
    if (ticks == 120){
        if (minute == 59){
            if (hour == 23){
                hour = 0;
                minute = 0;
                ticks = 0;
                // 00:00:00
            }
            else{
                hour++;
                minute = 0;
                ticks = 0;
                // XX:00:00
                voicePlayFlag = 1;
            }
        }
        else{
            minute++;
            ticks = 0;
            // XX:XX:00
        }
    }
    if (ticks % 2 == 1)
        dpDisplayFlag = 0;              // The beginning of the second part of the second
    else
        dpDisplayFlag = 1;
}

void interrupt timer_quick(void){       // Faster speed to present voice broadcasting: minute++ in every interrupt
    dpDisplayFlag = 0;
    if(minute == 0 && hour == 0)
        voicePlayFlag = 1;
    if(minute == 59){
        if(hour == 23){
            hour = 0;
            minute = 0;
        }
        else
            hour++;
        minute = 0;
        voicePlayFlag = 1;
    }
    else
        minute++;
}

void main()
{
    u8 index = 0;
    u8 keyResult = 0xff;
    u8 recAddr[12] = {ADDR_0, ADDR_1, ADDR_2, ADDR_3, ADDR_4, ADDR_5, ADDR_6, ADDR_7, ADDR_8, ADDR_9, ADDR_10, ADDR_TIP};
    init8255();
    initLED();                          // Display "HELLO 66"
    initisd1420(&keepMode);
    // Execute recording program
    while(1){
        if(keyResult == 0xff)
            keyResult = scanKeyboard();
        if(keyResult == 4){
            recSubProgram(&keepMode, recAddr[index]);
            delay(200);
            index++;
            keyResult = 0xff;
        }
        if(index > 11)
            break;
    }
    disable();
    init8259();
    setvect(8, timer_isr);
    // setvect(8, timer_quick);         // Present voice broadcasting function
    init8253();
    enable();
    while (1){
        scanDP(dpDisplayFlag);
        // Turn on/off dp according to displayFlag
        scanLED(minute, hour);
        // Display hour and minute all the time
        scanVoicePlayFlag(&keepMode, &voicePlayFlag, hour);
        // Play or not play voice broadcast according to flag
    }
}